package com.kum.service;

import com.alibaba.fastjson.JSONObject;
import com.kum.domain.entity.PeopleNear;
import com.kum.domain.entity.SysUserInfo;
import com.kum.utils.GeoHashUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class PeopleNearService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private GeoHashUtil geoHashUtil;

    @Autowired
    private SysUserInfoService userInfoService;

    /**
     * 向附近的人中添加数据
     *
     * @param peopleNear 附近的人实体类
     */
    public void add(PeopleNear peopleNear) {
        //对应redis原生命令:GEOADD user 116.48105 39.996794 zhangsan
        redisTemplate.opsForGeo().add(peopleNear.getCity(), new Point(peopleNear.getLng(), peopleNear.getLat()), peopleNear.getUserId());
        geoHashUtil.redisGeoAdd(peopleNear.getCity(), peopleNear.getLng(), peopleNear.getLat(), peopleNear.getUserId());
    }

    /**
     * 根据距离进行检索附近的人
     * @param key      一般为城市名称
     * @param userId   用户信息ID
     * @param distance 距离(1/km)
     * @param count    数量
     */
    public List<JSONObject> findByDistance(String key, String userId, Integer distance, Integer count) {
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = geoHashUtil.geoNearByPlace(key, userId, distance, count);
        List<JSONObject> result = new ArrayList<>();
        geoResults.getContent().forEach(item -> {

            JSONObject object = new JSONObject();
            String peopleNearUserId = item.getContent().getName();
            SysUserInfo userInfo = userInfoService.findById(peopleNearUserId);
            object.put("info",userInfo);
            object.put("distance",geoHashUtil.geoDist(key,userId,peopleNearUserId).getValue());
            result.add(object);

        });

        return result;
    }


}

